
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
import routes from './routes';

import store from '@/store'

// 先把VueRouter原型对象的push先保存一份
let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;

// 重写push|replace
VueRouter.prototype.push = function (location, resolve, reject) {
    if(resolve && reject) {
        // call||apply区别：
        // 相同点：都可以调用函数一次，都可以篡改函数的this一次
        // 区别：call传递参数用逗号隔开，apply方法传递数组
        originPush.call(this, location, resolve, reject)
    } else {
        originPush.call(this, location, ()=>{}, ()=>{})
    }
}
VueRouter.prototype.replace = function (location, resolve, reject) {
    if(resolve && reject) {
        originReplace.call(this, location, resolve, reject)
    } else {
        originReplace.call(this, location, ()=>{}, ()=>{})
    }
}
let router =  new VueRouter({
    routes,
    // 滚动行为
    scrollBehavior(to, from, savedPosition){
        // 返回y:0 代表滚动条在最上方
        return {y: 0}
    }
})

// 全局守卫，前置守卫，在路由跳转之前进行判断
router.beforeEach(async (to, from, next)=> {
    let token = store.state.user.token || localStorage.getItem("TOKEN")
    let name = store.state.user.userInfo.name
    if(token) {
        // 已登录
        if(to.path == '/login' || to.path == '/register') {
            next('/')
        } else {
            if(name){
                next()
            } else {
                try {
                    // 获取用户信息
                    await store.dispatch('getUserInfo')
                    next()
                } catch(error) {
                    // token失效
                   await store.dispatch('userLogout')
                   next('/login')
                }
            }
        }
    } else {
        // 未登录
        let toPath = to.path
        if(toPath.indexOf('/trade') != -1 || toPath.indexOf('/pay') != -1  || toPath.indexOf('/center') != -1) {
            next('/login?redirect='+toPath)
        } else {
            next()
        }
    }
})
export default router

